<template>
  <AppPage>
    <n-card rounded-10 flex-1>
      <div min-h-60 p-15 flex items-start b-1 bc-ccc rounded-8 bg="#fafafc" dark:bg-black mb-10>
        <n-select
          v-model:value="queryItems.categoryId"
          :options="categoryOptions"
          label-field="categoryName"
          value-field="id"
          placeholder="请选择分类"
          clearable
          style="width: 10%"
        />
        <n-input
          v-model:value="queryItems.title"
          type="text"
          placeholder="请输入文章标题"
          style="max-width: 30%"
          clearable
          @keydown.enter="$table?.handleSearch"
        >
        </n-input>
        <n-space wrap :size="[0, 15]" ml-auto>
          <n-button ml-10 type="primary" @click="$table?.handleSearch">搜索</n-button>
        </n-space>
      </div>

      <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :extra-params="extraParams"
        :scroll-x="1200"
        :columns="columns"
        :get-data="getBlogList"
        @on-checked="onChecked"
      >
      </CrudTable>

      <!-- 新增/编辑/查看 -->
      <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        :show-footer="modalAction !== 'view'"
        @on-save="handleSave"
      >
        <n-form ref="modalFormRef">
          <n-radio-group v-model:value="modalForm.visibleModel" name="visibleModel" default-value="public">
            <n-space>
              <n-radio v-for="item in visibility" :key="item.value" :value="item.value">
                {{ item.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
          <n-space v-if="modalForm.visibleModel === 'protect'" mt-40>
            <n-input
              v-model:value="modalForm.password"
              placeholder="请输入密码"
              type="password"
              show-password-on="mousedown"
            ></n-input>
          </n-space>

          <n-space
            v-if="modalForm.visibleModel === 'protect' || modalForm.visibleModel === 'public'"
            wrap
            :size="[5, 15]"
            flex
            mt-40
          >
            <n-switch v-model:value="modalForm.isTop" size="medium" /> 置顶
            <n-switch v-model:value="modalForm.isRecommend" size="medium" ml-10 /> 推荐
            <n-switch v-model:value="modalForm.isAppreciation" size="medium" ml-10 /> 赞赏
            <n-switch v-model:value="modalForm.isCommentEnabled" size="medium" ml-10 /> 评论
          </n-space>
        </n-form>
      </CrudModal>
    </n-card>
  </AppPage>
</template>

<script setup>
import { NButton, NSwitch } from 'naive-ui'
import { formatDateTime, renderIcon, isNullOrUndef } from '@/utils'
import { useCRUD } from '@/composables'
import { getBlogList, deleteBlogById, publishBlog, topBlog, updateBlogVisibility } from '@/api/blog/blog.js'
import { getCategoryDict } from '@/api/dict.js'

/** name的值要保持跟路由里面的name值一致，KeepAlive才会生效 */
defineOptions({ name: 'Blog' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
/** 补充参数（可选） */
const extraParams = ref()
const categoryOptions = ref([])

const router = useRouter()
const route = useRoute()

onActivated(() => {
  console.log('onActivated')
  $table.value?.handleSearch()
  getDictValue()
})

const visibility = [
  {
    value: 'public',
    label: '公开',
  },
  {
    value: 'private',
    label: '私密',
  },
  {
    value: 'protect',
    label: '密码保护',
  },
]

const columns = [
  {
    title: '序号',
    key: 'key',
    width: 30,
    align: 'center',
    render: (_, index) => {
      return `${index + 1}`
    },
  },
  {
    title: '标题',
    key: 'title',
    width: 200,
    align: 'center',
  },
  {
    title: '分类',
    key: 'categoryName',
    width: 60,
    align: 'center',
  },
  {
    title: '置顶',
    key: 'isTop',
    width: 20,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row['isTop'],
        loading: !!row.topping,
        onUpdateValue: () => handleisTop(row),
      })
    },
  },
  {
    title: '发布',
    key: 'isPublished',
    width: 20,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row['isPublished'],
        loading: !!row.publishing,
        onUpdateValue: () => handleisPublished(row),
      })
    },
  },
  {
    title: '可见性',
    key: 'visibility',
    width: 20,
    align: 'center',
    fixed: 'left',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleEdit(row),
          },
          { default: () => '可见性', icon: renderIcon('majesticons:eye-line', { size: 14 }) }
        ),
      ]
    },
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 100,
    align: 'center',
    render(row) {
      return h('span', formatDateTime(row['createTime']))
    },
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 100,
    align: 'center',
    render(row) {
      return h('span', formatDateTime(row['updateTime']))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 40,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 15px;',
            onClick: () => goEditBlogPage(row),
          },
          { default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', { size: 14 }) }
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 15px;',
            onClick: () => handleDelete(row.id),
          },
          { default: () => '删除', icon: renderIcon('material-symbols:delete-outline', { size: 14 }) }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}

function handleisPublished(row) {
  if (isNullOrUndef(row.id)) return
  row.publishing = true
  row.isPublished = !row.isPublished
  publishBlog(row.id, row.isPublished)
  row.publishing = false
  $message?.success(row.isPublished ? '已发布' : '已取消发布')
}

function handleisTop(row) {
  if (isNullOrUndef(row.id)) return
  row.topping = true
  row.isTop = !row.isTop
  topBlog(row.id, row.isTop)
  row.topping = false
  $message?.success(row.isTop ? '已置顶' : '已取消置顶')
}

function getDictValue() {
  getCategoryDict().then((res) => {
    // console.log(res.data)
    categoryOptions.value = res.data
  })
}

function goEditBlogPage(row) {
  router.push(`/blog/blog/edit/${row.id}`)
}

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '博客可见性',
  // initForm: { isTop: false, isPublished: false, isRecommend: false, isCommentEnable: false, isAppreciation: false },
  doDelete: deleteBlogById,
  doUpdate: updateBlogVisibility,
  refresh: () => $table.value?.handleSearch(),
})
</script>
